<?php
namespace app\api\service ;

use think\Request;
use think\Cache;

/** 
* Document
*/
class Token {
    
    public static function generateToken(){
        // 32位随机字符串
        $str32 = getRandChar(32);
        $time = time();
        $salt = \config('secret.tokenSalt');

        return md5($str32.$time.$salt);
    }
    /**
     * 从http请求头获取token
     *
     * @return string|false
     */
    public static function getFromHttp(){
        $res = Request::instance()->header('token');
        return $res ? $res : false;
    }
    /**
     * 获取token缓存的信息
     *
     * @param string $token
     * @return array|false|mixed
     */
    public static function getCacheValue($token,$field=''){
        $key = config('secret.tokenPre') . $token;
        $vars = Cache::get($key);
        if(empty($vars)){
            return false;
        }else{
            $vars = is_array($vars) ? $vars : json_decode($vars,true);
            if(empty($field)) {
                return $vars;
            }else{
                return array_key_exists($field,$vars)? $vars[$field] : '';
            }
        }
    }

}